package com.citycloud.ccuap.tc.admin.projectdefaultfunction;

import com.citycloud.ccuap.commons.constants.GlobalOperateType;
import com.citycloud.ccuap.commons.json.JSONData;
import com.citycloud.ccuap.commons.json.TreeNode;
import com.citycloud.ccuap.commons.openapi.controller.base.BaseController;
import com.citycloud.ccuap.commons.web.session.CurrentUser;
import com.citycloud.ccuap.commons.web.session.SessionConstant;
import com.citycloud.ccuap.commons.web.util.ResolveRequest;
import com.citycloud.ccuap.framework.exception.AppAssert;
import com.citycloud.ccuap.framework.mybatis.pagination.PageQuery;
import com.citycloud.ccuap.framework.util.ClassUtil;
import com.citycloud.ccuap.framework.util.DateUtil;
import com.citycloud.ccuap.framework.util.StringUtil;
import com.citycloud.ccuap.tc.admin.entity.SysProjectDefaultFunction;
import com.citycloud.ccuap.tc.admin.entity.SysProjectFunction;
import com.citycloud.ccuap.tc.admin.repository.SysDatagroupRepository;
import com.citycloud.ccuap.tc.admin.repository.SysProjectDefaultFunctionRepository;
import com.citycloud.ccuap.tc.admin.repository.SysProjectFunctionRepository;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.UUID;

import static org.springframework.data.domain.Sort.Direction.DESC;

@Api("项目（站点）默认菜单")
@RestController
@RequestMapping("/v1/yq/projectdefaultfunction")
public class ProjectDefaultFunctionController extends BaseController {

	@Autowired
	SysDatagroupRepository sysDatagroupRepository;
	@Autowired
    private IProjectDefaultFunctionService prjectDefaultFunctionService;
    
	
	/**
	 * 默认构造函数
	 */
	public ProjectDefaultFunctionController() {
	}

	@ApiOperation("根据主键获取对象")
	@RequestMapping(value = "/findById", method = { RequestMethod.GET, RequestMethod.POST })
	public JSONData findById() throws Exception {
		String funId = getStringParameter("funId");
		SysProjectDefaultFunction sysPrjectDefaultFunction = prjectDefaultFunctionService.findById(funId);
		
		JSONData jsonData = new JSONData(sysPrjectDefaultFunction);
		return jsonData;
	}
	
	/**
	 * 获取页面提交的对象
	 * 
	 * @return struts result
	 * @throws Exception
	 */
	private SysProjectDefaultFunction getRequestDataObject(short operateType) throws Exception {
		SysProjectDefaultFunction sysPrjectDefaultFunction = new SysProjectDefaultFunction();
		ResolveRequest.fillData(request, sysPrjectDefaultFunction);



		CurrentUser user = getCurrentUser();

		if (GlobalOperateType.ADD == operateType) {
			sysPrjectDefaultFunction.setCreator(user.getUser().getUserNo());
			sysPrjectDefaultFunction.setCreatedTime(DateUtil.getCurrentDateTime());
		} else if (GlobalOperateType.EDIT == operateType) {
			sysPrjectDefaultFunction.setUpdator(user.getUser().getUserNo());
			sysPrjectDefaultFunction.setUpdatedTime(DateUtil.getCurrentDateTime());
		}

		return sysPrjectDefaultFunction;
	}
	
	@ApiOperation("新增对象")
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public JSONData add() throws Exception {
		SysProjectDefaultFunction sysPrjectDefaultFunction = getRequestDataObject(GlobalOperateType.ADD);
//		AppAssert.isNull(prjectDefaultFunctionService.findById(sysPrjectDefaultFunction.getFunId()), "菜单编码已存在！");
//		AppAssert.isTrue(!sysPrjectDefaultFunction.getFunId().equals(sysPrjectDefaultFunction.getPid()), "当前菜单不能与上级菜单相同！");
		sysPrjectDefaultFunction.setFunId(UUID.randomUUID().toString().replace("-", ""));
		
		prjectDefaultFunctionService.insert(sysPrjectDefaultFunction);

		JSONData jsonData = new JSONData("添加项目（站点）默认菜单成功！");
		return jsonData;
	}

	@ApiOperation("更新对象")
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public JSONData update() throws Exception {
		SysProjectDefaultFunction sysPrjectDefaultFunction = getRequestDataObject(GlobalOperateType.EDIT);
		
		SysProjectDefaultFunction existSysFunction = prjectDefaultFunctionService.findById(sysPrjectDefaultFunction.getFunId());
		Assert.notNull(existSysFunction, "查询站点默认菜单为空！");
		String existFullPath = existSysFunction.getFullPath();
		String fullPath = sysPrjectDefaultFunction.getFullPath();
		if (!existFullPath.equals(fullPath)) {
			//批量修改全路径
			prjectDefaultFunctionService.updateFullPathBatch(sysPrjectDefaultFunction.getFunId(), existFullPath, fullPath);
		}
		
		prjectDefaultFunctionService.update(sysPrjectDefaultFunction);

		JSONData jsonData = new JSONData("修改项目（站点）默认菜单成功！");
		return jsonData;
	}
	

	@ApiOperation("删除对象")
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public JSONData delete() throws Exception {
		String funId = getStringParameter("funId");
		prjectDefaultFunctionService.deleteById(funId);
		
		JSONData jsonData = new JSONData("删除项目（站点）默认菜单成功！");
		return jsonData;
	}
	
	@ApiOperation("删除多个对象")
	@RequestMapping(value = "/deleteList", method = RequestMethod.POST)
	public JSONData deleteList() throws Exception {
		String funIds = getStringParameter("funIds");
		List<String> funIdList = StringUtil.strToStringList(funIds);
		
		prjectDefaultFunctionService.deleteIdList(funIdList);
		
		JSONData jsonData = new JSONData("删除项目（站点）默认菜单成功！");
		return jsonData;
	}

	@ApiOperation("根据条件查询对象")
	@RequestMapping(value = "/query", method = { RequestMethod.GET, RequestMethod.POST })
	public JSONData query() throws Exception {
		PageQuery<SysProjectDefaultFunction> pageQuery = ResolveRequest.getPageForParams(request);
		SysProjectDefaultFunctionDTO sysPrjectDefaultFunctionDTO = new SysProjectDefaultFunctionDTO();
		ResolveRequest.fillData(request, sysPrjectDefaultFunctionDTO, "q_", true);

		Sort sort = Sort.by(DESC, "createdTime");
//		Sort sort = new Sort(DESC, "createdTime");
		pageQuery.setSort(sort);
		
		
		PageQuery<SysProjectDefaultFunction> pageData = prjectDefaultFunctionService.selectPage(pageQuery, sysPrjectDefaultFunctionDTO);
		
		JSONData jsonData = new JSONData(pageData);
		return jsonData;
	}

	 @ApiOperation("查找树节点")
	 @RequestMapping(value = "/findNextChildNodeTree", method = { RequestMethod.GET, RequestMethod.POST })
	 public JSONData findNextChildNodeTree() throws Exception {
		String pid;
		String node = request.getParameter("node");
		if (node == null || "".equals(node) || "-1".equals(node)) {
			pid = null;
		} else {
			pid = String.valueOf(node);
		}
		
		List<TreeNode> treeNodeList;
		String funName = request.getParameter("nodeName");
		if (StringUtils.isBlank(funName)) {
			treeNodeList = prjectDefaultFunctionService.findNextChildNodeTree(pid);
		} else {
			treeNodeList = prjectDefaultFunctionService.findNodeTreeByName(funName);
		}
		
		JSONData jsonData = new JSONData(treeNodeList);
		return jsonData;
	 }
	 
	 @ApiOperation("删除节点")
	@RequestMapping(value = "/deleteNode", method = RequestMethod.POST)
	public JSONData deleteNode() throws Exception {
		String funId = getStringParameter("funId");
		prjectDefaultFunctionService.deleteNode(funId);
		
		JSONData jsonData = new JSONData("删除项目（站点）默认菜单节点成功！");
		return jsonData;
	}
	
	@ApiOperation("删除多个节点")
	@RequestMapping(value = "/deleteNodeList", method = RequestMethod.POST)
	public JSONData deleteNodeList() throws Exception {
		String funIds = getStringParameter("funIds");
		List<String> funIdList = StringUtil.strToStringList(funIds);
		prjectDefaultFunctionService.deleteNodeList(funIdList);
		
		JSONData jsonData = new JSONData("删除项目（站点）默认菜单节点成功！");
		return jsonData;
	}
	
	@ApiOperation("根据id查找名称")
	@RequestMapping(value = "/findNameById", method = { RequestMethod.GET, RequestMethod.POST })
	public JSONData findNameById() throws Exception {
		String funId = getStringParameter("funId");
		
		SysProjectDefaultFunction defaultFunction = prjectDefaultFunctionService.findById(funId);
		AppAssert.notNull(defaultFunction, "查询站点菜单对象为空！");
		
		JSONData jsonData = new JSONData("查询成功！");
		jsonData.setData(defaultFunction.getFunName());
		return jsonData;
	}


	@Autowired
	SysProjectDefaultFunctionRepository sysProjectDefaultFunctionRepository;

	@Autowired
	private SysProjectFunctionRepository sysProjectFunctionRepository;


	@ApiOperation("同步菜单树")
	@RequestMapping(value = "/syncFunction", method =  RequestMethod.POST )
	public JSONData syncFunction(@RequestBody  Map map) throws Exception {

		//站点ids
		List<String> projectIds= (List<String>) map.get("projectIds");

		//默认菜单id
		String functionId=(String)map.get("functionId");

		List<SysProjectDefaultFunction> defaultFunctionList= Lists.newArrayList();

		//获取当前数据
		SysProjectDefaultFunction defaultfunc=sysProjectDefaultFunctionRepository.findByFunId(functionId);

		//获取跟当前同级的节点
		List<SysProjectDefaultFunction> defaultFunctionListByPid=sysProjectDefaultFunctionRepository.findByPidOrderByOrderNo(defaultfunc.getPid());
		//获取当前funid作为pid的集合，即子节点
		List<SysProjectDefaultFunction> defaultfuncByPid=sysProjectDefaultFunctionRepository.findByPidOrderByOrderNo(functionId);

		defaultFunctionList.add(defaultfunc);

		if(defaultFunctionListByPid.size()>0){
			defaultFunctionList.addAll(defaultFunctionListByPid);
		}

		if(defaultfuncByPid.size()>0){
			defaultFunctionList.addAll(defaultfuncByPid);
		}

		for(String projectid :projectIds){

			for(SysProjectDefaultFunction sysProjectDefaultFunction :defaultFunctionList){

				SysProjectFunction sysProjectFunction=sysProjectFunctionRepository.findByFunId(sysProjectDefaultFunction.getFunId()+"_"+projectid);

				if(sysProjectFunction==null){
					SysProjectFunction sysProjectFunction2 = new SysProjectFunction();
					ClassUtil.copyProperties(sysProjectDefaultFunction, sysProjectFunction2);
					sysProjectFunction2.setProjectId(Long.valueOf(projectid));
					sysProjectFunction2.setFunId(sysProjectDefaultFunction.getFunId()+"_"+projectid);
					if(StringUtils.isNotEmpty(sysProjectDefaultFunction.getPid())) {
						sysProjectFunction2.setPid(sysProjectDefaultFunction.getPid()+"_"+projectid);
					}
					sysProjectFunctionRepository.insert(sysProjectFunction2);

                    if(defaultfunc.equals(sysProjectDefaultFunction)){

                        SysProjectFunction sysProject=sysProjectFunctionRepository.findByFunId(sysProjectFunction2.getPid());

                        if(sysProject==null){
                            sysProjectFunction2.setPid(null);

                            sysProjectFunction2.setFullPath(sysProjectFunction2.getFunName());

                            sysProjectFunctionRepository.update(sysProjectFunction2);

                        }

                    }
				}
			}





		}

//		SysProjectDefaultFunction defaultFunction = prjectDefaultFunctionService.findById(functionId);
//		AppAssert.notNull(defaultFunction, "查询站点菜单对象为空！");

		JSONData jsonData = new JSONData("同步成功！");

		return jsonData;
	}

}